/*jslint vars: true, forin:true, sloppy: true*/
/*global probe, angular */
(function () {
	var d3 = window.d3;
	//delete window.d3;

	function calcXScale (data) {
		var out = 7;
		angular.forEach(data, function (array) {
			out = Math.max(array.length, out);
		});

		return out - 1;
	}

	function calcYScale (data) {
		var out = 1;

		angular.forEach(data, function (array) {
			out = Math.max(out, Math.max.apply(Math, array));
		});

		return Math.ceil(out * 0.127) * 10;
	}
	
	probe.directive('lineChart', function () {
		return {
			restrict: 'E',
			replace: true,
			template: '<svg class="line-chart"></svg>',
			scope: {
				data: '=',
				option: '='
			},
			link: function (scope, element) {
				var group, x, y, xAxis, yAxis, line,
					width, height,
					margin = {
						top: 10,
						right: 10,
						bottom: 20,
						left: 30
					};

				scope.redraw = function () {
					if (!scope.data) {
						return;//no data yet
					}

					if (!group) {
						group = d3.select(element[0]).append('g');
					}
					width = scope.option.width;
					height = scope.option.height;

					x = d3.scale.linear().range([margin.left, width - margin.right]).domain([0, calcXScale(scope.data)]);
					y = d3.scale.linear().range([height - margin.top, margin.bottom]).domain([0, calcYScale(scope.data)]);

					xAxis = d3.svg.axis().scale(x).orient('bottom');
					yAxis = d3.svg.axis().scale(y).orient('left');

					d3.select(element[0]).selectAll('.axis').remove();//remove previous axis
					group.append('g').attr('transform', 'translate(0,' + (height - margin.top) + ')')
						.attr('class', 'x axis').call(xAxis);
					group.append('g').attr('transform', 'translate(' + (margin.left) + ',0)')
						.attr('class', 'y axis').call(yAxis);

					line = d3.svg.line().interpolate('basis').x(function (d, i) {
						return x(i);
					}).y(function (d) {
						return y(d);
					});

					group.selectAll('.line').remove();//remove previous lines

					angular.forEach(scope.data, function (value, key) {
						group.append('path')
							.attr('class', 'line ' + key)
							.attr('d', line(value));
					});

					if (scope.option.hide.length) {
						group.selectAll(scope.option.hide.map(function (string) {
							return '.' + string;
						}).join(',')).style({
							'opacity': 0
						});
					}
				};

				scope.$watch('data', scope.redraw, true);
				scope.$watchCollection('option.hide', scope.redraw, true);
			}
		}
	});
})();